//
//  KyAouthLoginViewController.swift
//  KySwiftPro
//
//  Created by fangyukui on 2017/10/25.
//  Copyright © 2017年 fangyukui. All rights reserved.
//

import UIKit
import SVProgressHUD

class KyAouthLoginViewController: UIViewController {
    lazy var webView = UIWebView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height))
    override func loadView() {
        super.loadView()
        webView.delegate = self
        view = webView
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        self.title = "登陆"
        setupUI()
        
        
    }
}


extension KyAouthLoginViewController{
    fileprivate func setupUI(){
    
//        https://api.weibo.com/oauth2/authorize?client_id=597084751&redirect_uri=http://www.baidu.com
        let url = "https://api.weibo.com/oauth2/authorize?client_id=" + "\(App_Key)" + "&redirect_uri=" + "\(RedirectUrl)"
        
        let request = URLRequest(url: URL(string:url)!)
        webView.loadRequest(request)
        
        
    }
}

extension KyAouthLoginViewController:UIWebViewDelegate{
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let url = request.url?.absoluteString  else {
             return false
        }
        if url.contains("code=") {
             let code = url.components(separatedBy: "code=")[1]
             KyNetworkManager.shared.requestAccessTocken(AuthoCode: code, complete: { (json, isSucess) in
                KyLog(message: json)
             })
             return false
        }
        return true
    }
    func webViewDidStartLoad(_ webView: UIWebView) {
         SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}
